Telegram Group & Telegram Channel
🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.



tg-me.com/cpluspluc/1034
Create:
Last Update:

🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1034

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

Telegram is riding high, adding tens of million of users this year. Now the bill is coming due.Telegram is one of the few significant social-media challengers to Facebook Inc., FB -1.90% on a trajectory toward one billion users active each month by the end of 2022, up from roughly 550 million today.

C Academy from tw


Telegram C++ Academy
FROM USA